
#include "communication.h"

int getListen(const char *ip, const short port)
{
    int sockfd_lisent;
    struct sockaddr_in service_addr;
    memset(&service_addr, 0, sizeof(service_addr));
    service_addr.sin_family = AF_INET;
    service_addr.sin_addr.s_addr = inet_addr(ip);
    service_addr.sin_port = htons(port);

    if ((sockfd_lisent = socket(AF_INET, SOCK_STREAM, 0)) == -1)
        syserr("socket cerate error\n");

    int opt = 1;
    if (setsockopt(sockfd_lisent, SOL_SOCKET, SO_REUSEPORT, &opt, sizeof(opt)) == -1)
    {
        syserr("setsockopt failed");
    };

    if (bind(sockfd_lisent, (struct sockaddr *)&service_addr, (socklen_t)sizeof(service_addr)) == -1)
        syserr("bind failed\n");

    if (listen(sockfd_lisent, 7) == -1)
        syserr("listen failed\n");
    return sockfd_lisent;
}

Client::Client(int sockfd)
{
    socket_com = accept(sockfd, (sockaddr *)&client_addr, &socklen);
    if (socket_com == -1)
    {
        // 保存错误信息
        error_message = "accept client error";
        error_message += strerror(errno);
    }
    else
    {
        error_message = "succeed";
    }
}

void *Client::readClinet(unsigned int datalen)
{
    if (data_size < datalen)
    {
        // 重新分配空间
        data = (char *)realloc(data, datalen);
        if (data != nullptr)
        {
            data_size = datalen;
        }
    }
    memset(data, 0, data_size);

    data_len = 0;
    int len = 0;
    while (datalen != 0)
    {
        len = read(socket_com, data + data_len, datalen);
        if (len == -1)
        {
            error_message = "read error";
            error_message += strerror(errno);
            return nullptr;
        }
        else if (len == 0)
        {
            error_message = "client close";
            error_message += strerror(errno);
            return nullptr;
        }
        data_len += len;
        datalen -= len;
    }
    error_message = "succeed";
    return data;
}

void Client::writeClinet(const void *data, unsigned int datalen)
{
    if (write(socket_com, data, datalen) == -1)
    {
        error_message = "write failed";
        error_message += strerror(errno);
    }
    error_message = "succeed";
}